import { Component } from '@angular/core';
import { Position } from './position';

import { OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

import { PositionService } from './position.service';

declare var AMap;

@Component({
  selector: 'my-positions',
  templateUrl: './position.component.html',
  styles: [require('./position.scss')],

})

export class PositionComponent implements OnInit {
  ngOnInit() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 10,
      center: [121.473662, 31.230372]
    });
    this.timerInterval = 5000;
    this.markers = [];
    this.timerId = setInterval(() => { this.getPositions(); }, this.timerInterval);
  }
  timerInterval: number;//刷新间隔

  timerId: any;
  public map: any;
  positions: Position[];
  markers:any[];

  constructor(
    private positionService: PositionService) {
  }

  getPositions() {
    this.positionService.getPosition().then(pos => this.positions = pos);
    this.markBus();
  }

  markBus() {
    if (this.markers) {
      this.map.remove(this.markers);
    }

    if (this.positions) {
      for (var i = 0; i < this.positions.length; i++) {
        let content = '<div><i class="fa fa-car" aria-hidden="true"></i>' + this.positions[i].title  +'</div>';
        var marker = new AMap.Marker({
          position: this.positions[i].position.split(','),
          title: this.positions[i].title
        });
        marker.setMap(this.map);

        this.markers.push(marker);
      }
    }
  }

  ngOnDestroy() {
    clearInterval(this.timerId);
  }
}
